//
//  ViewController.swift
//  68.新工程-表情键盘_界面搭建
//
//  Created by shenzhenIOS on 16/4/18.
//  Copyright © 2016年 shenzhenIOS. All rights reserved.
//

import UIKit

class ViewController: UIViewController {

    @IBOutlet weak var textView: UITextView!
    override func viewDidLoad() {
        super.viewDidLoad()

        // 使用自定义的view作为键盘
        let keyboard = HMEmoticonKeyboard()
        keyboard.textView = textView
        textView.inputView = keyboard
        
        textView.becomeFirstResponder()
        
        NSHomeDirectory()
        print("NSHomeDirectory(): \(NSHomeDirectory())")
        
//        let packages1 = HMEmoticonManager.sharedManager.packageModels
//        let packages2 = HMEmoticonManager.sharedManager.packageModels
//        let packages3 = HMEmoticonManager.sharedManager.packageModels
//        print("packages1: \(packages1)")
        
//        emojiDemo()
    }
    
    @IBAction func getText(sender: AnyObject) {
        let text = textView.emoticonText()
        print("表情文本: \(text)")
    }
    
    private func emoticonText() {
        //        print("文本内容: \(textView.attributedText)")
        
        var strM = ""
        /// 属性文本会分段保存.普通文本一段, emoji是一段, 附件是一段
        /// 获取属性文本中的每一段
        textView.attributedText.enumerateAttributesInRange(NSRange(location: 0, length: textView.attributedText.length), options: []) { (dict, range, _) -> Void in
            // 每当获取到一段内容就会调用闭包一次
            // 会返回每段的range
            // 图片表情 dict里面会包含 NSAttachment key, 获取图片表情的名称
            if let attachment = dict["NSAttachment"] as? HMTextAttachment {
                // 附件 chs
                strM += attachment.chs!
            } else {
                // 普通文本和emoji表情,直接截取获取对应的内容range
                let text = (self.textView.attributedText.string as NSString).substringWithRange(range)
                
                // 将截取的文本拼接起来
                strM += text
            }
            print("dict: \(dict)")
            print("range: \(range)")
            print("---------")
        }
        print("strM: \(strM)")
    }
    
    
    private func emojiDemo() {
        let code = "0x1f60d"
        
        // 扫描 String -> Int
        let scanner = NSScanner(string: code)
        
        var result: UInt32 = 0
        // result: UnsafeMutablePointer<UInt32>: 需要一个UInt32类型的可变指针
        scanner.scanHexInt(&result)
        
        print("result: \(result)")
        
        let scalar = UnicodeScalar(result)
        let c = Character(scalar)
        let emoji = String(c)
        
        print("emoji: \(emoji)")
        
        textView.text = emoji
    }
}

